/**
 * @函数功能:分页、导出、列表多选
 *
 */
export const exportMixin = {
  data() {
    return {
      selections: {}, //保存已选择过的row
    };
  },
  methods: {
    //当用户手动勾选数据行的 Checkbox 时触发的事件
    select(selection, row) {
      if (this.selections[row.id]) {
        delete this.selections[row.id];
      } else {
        this.selections[row.id] = row;
      }
    },
    //当用户手动勾选全选 Checkbox 时触发的事件
    selectAll(selection) {
      //全选
      if (selection.length) {
        selection.forEach((row) => {
          this.selections[row.id] = row;
        });
      } else {
        // 取消全选
        this.tableData.forEach((row) => {
          delete this.selections[row.id];
        });
      }
    },
    //点击导出按钮
    exportSel() {
      if (this.getSelRowLen() === 0) {
        this.message.warning({ message: "请选择" });
        return;
      }
      let ids = this.getSelIds();
      console.info("[exportSel] ids:", ids);
      this.exportData(ids); //调取接口进行下载
    },

    //点击导出按钮
    copySelRules() {
      if (this.getSelRowLen() === 0) {
        this.message.warning({ message: "请选择" });
        return;
      }
      let ruleIds = this.getCheckedRuleIds();
      console.info("[copySelRules] ruleIds:", ruleIds);
      this.callCopyRulesApi(ruleIds); //调取接口进行下载
    },

    //点击分页回显选中的状态
    selEcho(data) {
      let ids = this.getSelIds();
      let rows = [];
      if (data) {
        rows = data.filter((row) => {
          return ids.includes(row.id);
        });
      } else {
        rows = this.tableData.filter((row) => {
          return ids.includes(row.id);
        });
      }
      this.$nextTick(() => {
        rows.map((row) => {
          this.$refs.uebaTable.toggleRowSelection(row);
        });
      });
    },
    //下载选中的数据
    //data:接口请求过来的数据，cb：回调函数
    downSelData(data, cb) {
      let downEle = document.createElement("a");
      downEle.href = data.fileUrl;
      downEle.setAttribute("download", "");
      document.body.appendChild(downEle);
      downEle.click();
      document.body.removeChild(downEle);

      //初始化工作
      this.$refs && this.$refs.uebaTable && this.$refs.uebaTable.clearSelection();
      this.selections = {}; //导出之后清空
      cb && cb();
    },
    //获取选择的id
    getSelIds() {
      let selections = Object.keys(this.selections);
      return selections.map((item) => Number(item));
    },

    /**
     * 获取选择的rule_id集合
     * @returns
     */
    getCheckedRuleIds() {
      let ruleIds = [];
      for (const [key, value] of Object.entries(this.selections)) {
        // console.info("[getCheckedRuleIds] key:%d", key, value);
        let ruleId = value["rule_id"];
        ruleIds.push(ruleId);
      }
      return ruleIds;
    },

    //获取选中行的长度
    getSelRowLen() {
      return Object.keys(this.selections).length;
    },
    //获取行的某个字段数据
    getSelRowsFieldData(field) {
      let arr = [];
      for (let key in this.selections) {
        let row = this.selections[key];
        arr.push(row[field]);
      }
      return arr;
    },
  },
};
